/**
 * File: XmlController.java
 *
 * $Id: XmlServiceImpl.java,v 1.1 2009-08-13 17:51:29 chris Exp $
 * Author: $Author: chris $
 * Version: $Rev$
 * 
 */
package uk.ac.manchester.tewpl.iceiface.server.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.explorium.api.exception.KnowledgeBaseException;
import org.explorium.api.model.KBClass;
import org.explorium.api.model.KBObjectProperty;
import org.explorium.api.model.KBResource;
import org.explorium.api.repository.kb.KBRepositoryProvider;
import org.explorium.api.repository.kb.KBRepositoryProviderManager;
import org.explorium.api.repository.kb.KnowledgeBase;
import org.explorium.core.bus.Bus;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;

/**
 * @author chris
 *
 */
@Controller
@RequestMapping("/xml/*")
public class XmlServiceImpl {
	private static final Log LOG = LogFactory
		.getLog(XmlServiceImpl.class);
	@Autowired
	private Bus bus;
	private KBRepositoryProvider provider;
	private KnowledgeBase kb;

	public void setBus(Bus bus) {
		this.bus = bus;

		// Set KnowledgeBase Repository Provider
		this.provider = bus.getExtension(KBRepositoryProviderManager.class)
				.getKBRepositoryProvider("owl");
		if (this.provider == null) {
			LOG.debug("Provider is NULL :-(");
		}
	}
	
	@RequestMapping
	public void classList(HttpServletResponse response, @RequestParam String kbURI, @RequestParam String wsURI) throws KnowledgeBaseException, IOException{
		if (kbURI == "") kbURI = "urn:jisc:ib";
		kb = provider.getKnowledgeBase(kbURI);
		
		kb.startTransaction();
		kb.setActiveWorkspace(wsURI);
		boolean reasoning = kb.getReasoning();
		kb.setReasoning(true);
		Collection<KBClass> classes = kb.findClasses();
		kb.setReasoning(reasoning);
		kb.commitTransaction();
		
		List<String> nodes = new ArrayList<String>();
		
		if (classes != null){
			for(KBClass cls : classes){
				nodes.add(printNode(cls));
			}
		}
		
		//return output
		Iterator<String> it = nodes.iterator();
		response.getOutputStream().println("<classList>");
		while (it.hasNext()){
			response.getOutputStream().println(it.next());
		}
		response.getOutputStream().println("</classList>");
		response.getOutputStream().flush();
	}
	

	String printNode(KBClass cls) {
		StringBuffer sb = new StringBuffer();
		sb.append("<Node ");
		sb.append("id=\"" + cls.getUri() + "\" ");
		String label;
		try {
			label = cls.getLabel().getValue();
		} catch (NullPointerException e) {
			label = cls.getLocalPart();
		}
		sb.append("name=\"" + label + "\" ");
		//sb.append("desc=\"" +  "Desc \" ");
		sb.append(">");
		sb.append(printRelations(cls)+"\n");
		sb.append("</Node>");
		
		return sb.toString();
	}
	
	String printRelations(KBClass cls){
		StringBuffer sb = new StringBuffer();
		
		Collection<KBObjectProperty> ops = kb.findClassObjectProperties(cls.getUri());
		
		for(KBObjectProperty op : ops){
			String relLabel;
			try {
				relLabel = op.getLabel().getValue();
			} catch (NullPointerException e) {
				relLabel = "";
			}
			Iterator<KBClass> range = op.getRange().iterator();
			while (range.hasNext()){
				KBClass destcls = range.next();
				String dest = destcls.getUri();
				String destName;
				try {
					destName = destcls.getLabel().getValue();
				} catch (NullPointerException e) {
					destName = destcls.getLocalPart();
				}
				sb.append("\n\t<Link ");
				sb.append("dest=\""+ dest +"\" ");
				sb.append("destName=\""+destName+"\" ");
				sb.append("label = \""+ relLabel +"\" ");
				sb.append("/>");
			}
		}
		
		return sb.toString();
	}

//	String printEdge(KBResource source, KBResource target, String label) {
//
//		StringBuffer sb = new StringBuffer();
//		sb.append("<Edge ");
//		sb.append("fromID=\"" + source.getUri() + "\" ");
//		sb.append("toID=\"" + target.getUri() + "\" ");
//		sb.append("edgeLabel=\"" + label + "\" ");
//		sb.append("flow=\"50\" ");
//		sb.append("edgeClass=\"sun\" ");
//		sb.append("edgeIcon=\"org/un/cava/birdeye/assets/edges/NoChange.png\" ");
//		sb.append("/>");
//		
//		return sb.toString();
//	}
	
		
}
